package cn.com.backstage.controller;

import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.com.api.entity.ApiT_city;
import cn.com.api.entity.ApiT_dingass;
import cn.com.api.entity.ApiT_dingdan;
import cn.com.api.entity.ApiTmember;
import cn.com.api.entity.Cond;
import cn.com.api.service.ApiMemberService;
import cn.com.api.service.ApiOrderService;
import cn.com.api.service.ApiT_dingassService;
import cn.com.api.service.ApiT_dingdanService;
import cn.com.api.service.StartOnLoadService;
import cn.com.backstage.controller.base.T_dingdanBaseController;
import cn.com.util.*;

@Controller
@RequestMapping(Utils.SYS_BACKSTAGE + "/")
public class T_dingdanController extends T_dingdanBaseController {

	private static Logger logger = Logger.getLogger(T_dingdanController.class);

	@Autowired
	private ApiT_dingdanService apiT_dingdanService;
	@Autowired
	private ApiT_dingassService apiT_dingassService;
	@Autowired
	private ApiOrderService apiOrderService;
	@Autowired
	private ApiMemberService apiMemberService;

	@Autowired
	private StartOnLoadService startOnLoadService;

	/**
	 * 商铺订单管理查询界面
	 * 
	 * @return
	 */
	@RequestMapping(value = "shop-order")
	public ModelAndView shop_order(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("forward:/backstage/shop_order.jsp");
		List<Map<String, Object>> order = new ArrayList<Map<String, Object>>();
		List<Map<String, Object>> psy = new ArrayList<Map<String, Object>>();
		psy = apiMemberService.searMemberByType("3");
		Cond con = new Cond();
		String status = request.getParameter("status");
		String mobile = request.getParameter("mobile");
		String titles = request.getParameter("titles");
		String name = request.getParameter("name");
		String zftype = request.getParameter("zftype");
		String cmob = request.getParameter("cmob");
		String stime = request.getParameter("stime");
		String etime = request.getParameter("etime");
		con.setMobile(mobile != null ? mobile.trim() : "");
		con.setTitles(titles != null ? titles.trim() : "");
		con.setName(name != null ? name.trim() : "");
		con.setStime(stime != null ? stime : "");
		con.setEtime(etime != null ? etime : "");
		con.setZftype1("-1".equals(zftype) ? "" : zftype);
		if (zftype == null) {
			con.setZftype1("");
			zftype = "-1";
		}
		con.setCmob(cmob != null ? cmob.trim() : "");
		con.setEnable("");
		con.setZistatus("");
		con.setZistatus1("");
		con.setZftype("");
		// con.setSpstatus(new String[]{});
		// con.setDdstatus(new String[]{});
		if ("1".equals(status)) {
			con.setDdstatus(new String[] { "1", "2", "3", "4", "5", "6" });
			con.setSpstatus(new String[] { "0", "1", "2", "3", "4", "6" });
		} else if ("2".equals(status)) {
			con.setEnable("1");
			con.setDdstatus(new String[] { "1" });
			con.setZistatus("1");
			con.setZistatus1("0");
			con.setZftype("3");
		} else if ("3".equals(status)) {
			con.setSpstatus(new String[] { "0", "1", "2", "3" });
		} else if ("4".equals(status)) {
			con.setSpstatus(new String[] { "4", "5" });
		} else if ("5".equals(status)) {
			con.setEnable("5");
		} else {
			con.setDdstatus(new String[] { "1", "2", "3", "4", "5", "6" });
			con.setSpstatus(new String[] { "0", "1", "2", "3", "4", "6" });
		}
		order = apiOrderService.backShopOrder(con);
		mv.addObject("orders", order);
		Map<String, Object> cond = new HashMap<String, Object>();
		cond.put("status", status != null ? status : "1");
		cond.put("mobile", mobile);
		cond.put("titles", titles);
		cond.put("name", name);
		cond.put("zftype", zftype);
		cond.put("cmob", cmob);
		cond.put("stime", stime);
		cond.put("etime", etime);
		mv.addObject("cond", cond);
		mv.addObject("psy", psy);

		return mv;
	}

	/**
	 * 商铺（非自营）订单list
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "shop-order-list")
	public ModelAndView shopOrderList(HttpServletRequest request, HttpServletResponse response, PageInfo pageInfo)
			throws Exception {
		ModelAndView mv = new ModelAndView("forward:/backstage/shop-order_list.jsp");
		List<Map<String, Object>> psy = apiMemberService.searMemberByType("3");

		Map<String, Object> conditions = new HashMap<String, Object>();

		List<ApiT_city> cities = startOnLoadService.citys();

		String title = request.getParameter("title");
		String mobile = request.getParameter("mobile");
		String zftype = request.getParameter("zftype");
		String status = request.getParameter("status");
		String name = request.getParameter("name");
		String cName = request.getParameter("cName");// 快递员姓名
		String stime = request.getParameter("stime");
		String etime = request.getParameter("etime");
		String cityId = request.getParameter("cityId");
		String c_sname = request.getParameter("c_sname");// 商店名称
		conditions.put("isZiYing", false);
		conditions.put("title", title != null ? title.trim() : title);
		conditions.put("mobile", mobile != null ? mobile.trim() : mobile);
		conditions.put("zftype", zftype != null ? zftype.trim() : zftype);
		conditions.put("status", status != null ? status.trim() : status);
		conditions.put("name", name != null ? name.trim() : name);
		conditions.put("cName", cName != null ? cName.trim() : cName);
		conditions.put("stime", stime);
		conditions.put("etime", etime);
		conditions.put("cityId", cityId);
		conditions.put("c_sname", c_sname);
		List<Map<String, Object>> orders = apiOrderService.searchOrder(conditions, pageInfo);

		mv.addObject("orders", orders);
		mv.addObject("psy", psy);
		mv.addObject("conditions", conditions);
		mv.addObject("pageInfo", pageInfo);
		mv.addObject("citys", cities);

		return mv;
	}

	/**
	 * 请求取消订单
	 *
	 * @return
	 */
	@RequestMapping(value = "request-cancle-order")
	public ModelAndView article_add_pre(String orderId) throws Exception {
		ModelAndView mv = new ModelAndView("forward:/backstage/cancle_order.jsp");

		ApiT_dingdan dingdan = apiT_dingdanService.findbytitles(orderId);
		mv.addObject("dingdan", dingdan);
		return mv;
	}

	/**
	 * 确认取消订单
	 * 
	 * @param duty
	 *            1：商家; 2：配送员
	 * @param remark
	 *            取消原因
	 */
	@RequestMapping(value = "cancle-order")
	public @ResponseBody Map<String, Object> cancleShopOrder(String orderId, String duty, String remark) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			result = apiT_dingdanService.cancleOrder(orderId, duty, remark);
		} catch (Exception ex) {
			result.put("error", "-1");
			result.put("information", "发生异常");
			logger.error(Util.getStackTraceAsString(ex));
		}
		return result;
	}

	/**
	 * 自营订单list
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "order-list")
	public ModelAndView orderList(HttpServletRequest request, HttpServletResponse response, PageInfo pageInfo)
			throws Exception {
		ModelAndView mv = new ModelAndView("forward:/backstage/order_list.jsp");
		List<Map<String, Object>> psy = apiMemberService.searMemberByType("3");

		Map<String, Object> conditions = new HashMap<String, Object>();

		List<ApiT_city> cities = startOnLoadService.citys();

		String title = request.getParameter("title");
		String mobile = request.getParameter("mobile");
		String zftype = request.getParameter("zftype");
		String status = request.getParameter("status");
		String name = request.getParameter("name");
		String cName = request.getParameter("cName");// 快递员姓名
		String stime = request.getParameter("stime");
		String etime = request.getParameter("etime");
		String cityId = request.getParameter("cityId");
		String is_print = request.getParameter("is_print");
		conditions.put("isZiYing", true);
		conditions.put("title", title != null ? title.trim() : title);
		conditions.put("mobile", mobile != null ? mobile.trim() : mobile);
		conditions.put("zftype", zftype != null ? zftype.trim() : zftype);
		conditions.put("status", status != null ? status.trim() : status);
		conditions.put("name", name != null ? name.trim() : name);
		conditions.put("cName", cName != null ? cName.trim() : cName);
		conditions.put("stime", stime);
		conditions.put("etime", etime);
		conditions.put("cityId", cityId);
		conditions.put("is_print", is_print);
		List<Map<String, Object>> orders = apiOrderService.searchOrder(conditions, pageInfo);

		mv.addObject("orders", orders);
		mv.addObject("psy", psy);
		mv.addObject("conditions", conditions);
		mv.addObject("pageInfo", pageInfo);
		mv.addObject("citys", cities);

		return mv;
	}

	/**
	 * 自营订单list
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "order_alarm-list")
	public ModelAndView order_alarm_List(HttpServletRequest request, HttpServletResponse response, PageInfo pageInfo)
			throws Exception {
		ModelAndView mv = new ModelAndView("forward:/backstage/order_alarm_list.jsp");
		List<Map<String, Object>> psy = apiMemberService.searMemberByType("3");

		Map<String, Object> conditions = new HashMap<String, Object>();

		List<ApiT_city> cities = startOnLoadService.citys();

		String title = request.getParameter("title");
		String mobile = request.getParameter("mobile");
		String zftype = request.getParameter("zftype");
		String status = request.getParameter("status");
		String name = request.getParameter("name");
		String cName = request.getParameter("cName");// 快递员姓名
		String stime = request.getParameter("stime");
		String etime = request.getParameter("etime");
		String cityId = request.getParameter("cityId");
		// conditions.put("isZiYing", true);
		conditions.put("title", title != null ? title.trim() : title);
		conditions.put("mobile", mobile != null ? mobile.trim() : mobile);
		conditions.put("zftype", zftype != null ? zftype.trim() : zftype);
		conditions.put("status", "1");
		conditions.put("name", name != null ? name.trim() : name);
		conditions.put("cName", cName != null ? cName.trim() : cName);
		conditions.put("stime", stime);
		conditions.put("etime", etime);
		conditions.put("cityId", cityId);

		pageInfo.setShowCount(100);
		List<Map<String, Object>> orders = apiOrderService.searchOrder(conditions, pageInfo);

		Calendar cal = Calendar.getInstance(); // 使用默认时区和语言环境获得一个日历。
		cal.add(Calendar.MINUTE, -5);// 五分钟前
		Date date_1 = cal.getTime();

		Calendar cal2 = Calendar.getInstance();
		cal2.add(Calendar.MINUTE, -15);// 十五分钟前
		Date date_2 = cal2.getTime();

		Calendar cal3 = Calendar.getInstance();
		cal3.add(Calendar.MINUTE, -30);// 三十分钟前
		Date date_3 = cal3.getTime();

		// alarm_level
		for (Map<String, Object> order : orders) {
			Object date_str = order.get("appdate");
			Date date_app = new Date();
			SimpleDateFormat newstr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			date_app = newstr.parse((String) date_str);// 下单时间

			if (date_app.compareTo(date_3) < 0) {
				order.put("alarm_level", 1);
			} else if (date_app.compareTo(date_2) < 0) {
				order.put("alarm_level", 2);
			} else if (date_app.compareTo(date_1) < 0) {
				order.put("alarm_level", 3);
			}

		}

		mv.addObject("orders", orders);
		mv.addObject("psy", psy);
		mv.addObject("conditions", conditions);

		mv.addObject("pageInfo", pageInfo);
		mv.addObject("citys", cities);

		return mv;
	}

	/**
	 * 自营订单刷新
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "order_alarm-list-refresh")
	public void order_alarm_List_refresh(HttpServletRequest request, HttpServletResponse response, PageInfo pageInfo)
			throws Exception {

		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> conditions = new HashMap<String, Object>();

		String title = request.getParameter("title");
		String mobile = request.getParameter("mobile");
		String zftype = request.getParameter("zftype");
		String status = request.getParameter("status");
		String name = request.getParameter("name");
		String cName = request.getParameter("cName");// 快递员姓名
		String stime = request.getParameter("stime");
		String etime = request.getParameter("etime");
		String cityId = request.getParameter("cityId");
		conditions.put("isZiYing", true);
		conditions.put("title", title != null ? title.trim() : title);
		conditions.put("mobile", mobile != null ? mobile.trim() : mobile);
		conditions.put("zftype", zftype != null ? zftype.trim() : zftype);
		conditions.put("status", status != null ? status.trim() : status);
		conditions.put("name", name != null ? name.trim() : name);
		conditions.put("cName", cName != null ? cName.trim() : cName);
		conditions.put("stime", stime);
		conditions.put("etime", etime);
		conditions.put("cityId", cityId);

		// pageInfo.setShowCount(20);
		List<Map<String, Object>> orders = apiOrderService.searchOrder(conditions, pageInfo);

		// alarm_level
		for (Map<String, Object> order : orders) {
			Object date_str = order.get("appdate");
			Date date_app = new Date();
			SimpleDateFormat newstr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			date_app = newstr.parse((String) date_str);

			Calendar cal = Calendar.getInstance(); // 使用默认时区和语言环境获得一个日历。
			cal.add(Calendar.HOUR_OF_DAY, -10);
			Date date_1 = cal.getTime();
			Calendar cal2 = Calendar.getInstance();
			cal2.add(Calendar.HOUR_OF_DAY, -20);
			Date date_2 = cal2.getTime();
			if (date_app.compareTo(date_1) < 0) {
				order.put("alarm_level", 2);
			} else if (date_app.compareTo(date_1) > 0 && date_app.compareTo(date_2) < 0) {
				order.put("alarm_level", 1);
			} else {
				order.put("alarm_level", 3);
			}

		}

		List<ApiT_city> cities = startOnLoadService.citys();

		// mv.addObject("orders",orders);
		// mv.addObject("conditions", conditions);
		// mv.addObject("pageInfo", pageInfo);
		// mv.addObject("citys",cities);
		// StringBuilder
		map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
		map.put(Utils.MESSAGE, "修改成功！");
		//
		PrintWriter out = response.getWriter();
		out.print(JsonUtil.object2json(map));
		out.close();
	}

	/**
	 * 根据订单id查询订单详情
	 * 
	 * @param rid
	 * @return
	 */
	@RequestMapping(value = "order-details")
	public ModelAndView orderDetails(Integer rid) {
		ModelAndView mv = new ModelAndView("forward:/backstage/order_details.jsp");
		ApiT_dingdan dingdan = apiT_dingdanService.findDingDanInfo(rid);
		if (dingdan != null) {
			ApiT_dingass gassCons = new ApiT_dingass();
			gassCons.setDid(dingdan.getRid() + "");
			List<ApiT_dingass> dingAsses = apiT_dingassService.findDingAsseInfos(gassCons);
			mv.addObject("dingAsses", dingAsses);

			if (dingdan.getZi_status() == 1) {// 已经支付成功,计算第三方所支付的金额
				double payMoney = dingdan.getPaymoney();
				double remainMoney = dingdan.getRemainmoney();

				if (!dingdan.getZf_type().equals("3")) {// 排除货到付款
					DecimalFormat df = new DecimalFormat("0.00");
					String onlinPayMoney = df.format(Math.abs(payMoney - remainMoney));// 第三方支付的金额
					dingdan.setOnlinPayMoney(onlinPayMoney);
				} else {
					dingdan.setOnlinPayMoney("0.00");
				}

			}

			// 下订单的用户的信息
			ApiTmember member = apiMemberService.findMemberByCuserid(dingdan.getUid());
			System.out.println(member.getCcname());

			mv.addObject("dingdan", dingdan);
		}
		return mv;
	}

	// 根据订单titles查询订单详情
	@RequestMapping(value = "order-detailsbytitles")
	public ModelAndView orderDetailsbytitles(String titles) {
		ModelAndView mv = new ModelAndView("forward:/backstage/order_details.jsp");
		ApiT_dingdan dingdan = apiT_dingdanService.findbytitles(titles);
		if (dingdan != null) {
			ApiT_dingass gassCons = new ApiT_dingass();
			gassCons.setDid(dingdan.getRid() + "");
			List<ApiT_dingass> dingAsses = apiT_dingassService.findDingAsseInfos(gassCons);
			mv.addObject("dingAsses", dingAsses);

			if (dingdan.getZi_status() == 1) {// 已经支付成功,计算第三方所支付的金额
				double payMoney = dingdan.getPaymoney();
				double remainMoney = dingdan.getRemainmoney();

				if (!dingdan.getZf_type().equals("3")) {// 排除货到付款
					DecimalFormat df = new DecimalFormat("0.00");
					String onlinPayMoney = df.format(Math.abs(payMoney - remainMoney));// 第三方支付的金额
					dingdan.setOnlinPayMoney(onlinPayMoney);
				} else {
					dingdan.setOnlinPayMoney("0.00");
				}
			}
			mv.addObject("dingdan", dingdan);
		}
		return mv;
	}

	/**
	 * 批量打印订单
	 * 
	 * @param orderIds
	 *            订单id (自增长的id)
	 * @return
	 */
	@RequestMapping(value = "orders-print")
	public ModelAndView printOrders(Integer[] orderIds) {
		ModelAndView mv = new ModelAndView("forward:/backstage/orders_print.jsp");
		List<ApiT_dingdan> dingdans = apiT_dingdanService.batchDingDansInfo(orderIds);
		for (ApiT_dingdan dingdan : dingdans) {
			ApiT_dingass gassCons = new ApiT_dingass();
			gassCons.setDid(dingdan.getRid() + "");
			List<ApiT_dingass> dingAsses = apiT_dingassService.findDingAsseInfos(gassCons);
			dingdan.setDingAsses(dingAsses);

			if (dingdan.getZi_status() == 1) {// 已经支付成功,计算第三方所支付的金额
				double payMoney = dingdan.getPaymoney();
				double remainMoney = dingdan.getRemainmoney();

				if (!dingdan.getZf_type().equals("3")) {// 排除货到付款
					DecimalFormat df = new DecimalFormat("0.00");
					String onlinPayMoney = df.format(Math.abs(payMoney - remainMoney));// 第三方支付的金额
					dingdan.setOnlinPayMoney(onlinPayMoney);
				} else {
					dingdan.setOnlinPayMoney("0.00");
				}
			}
		}

		// 批量更新订单的打印状态
		apiT_dingdanService.batchUpdateDingdanPrintStatus(orderIds);
		mv.addObject("dingdans", dingdans);
		return mv;
	}

	/**
	 * 更新订单
	 * 
	 * @param rid
	 * @return
	 */
	@RequestMapping(value = "order-update")
	public @ResponseBody Map<String, Object> updateOrder(ApiT_dingdan newDingdan) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			int count = apiT_dingdanService.updateDingdan(newDingdan);
			if (count > 0) {
				result.put("error", Utils.RESULT_RC_SUCCESS);
				result.put("information", "更新成功");
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			result.put("error", Utils.RESULT_RC_EXCEPTION);
			result.put("information", "发生异常");
		}
		return result;
	}

}
